Practical Julia: A Hands-On Introduction for Scientific Minds by Lee Phillips

Practical Julia: A Hands-On Introduction for Scientific Minds by Lee Phillips

Author:Lee Phillips
Language: eng
Format: epub, mobi
Publisher: No Starch Press, Inc.
Published: 2024-09-15T00:00:00+00:00


Defining structs with Base.@kwdef

The default method for defining composite types leaves a bit to be desired. Its main deficiency is that the constructor it creates requires the programmer to remember the order in which a type’s fields appear in its definition. The Base.@kwdef macro improves on this limitation by creating constructors that we can use with field names. For repeated use, it’s convenient to import this macro and rename it: import Base.@kwdef as @kwdef.

Let’s expand our geometry package with a new type representing ellipses as shown in Listing 8-5. This time we’ll use @kwdef.

@kwdef struct Ellipse axis1::Real = 1 axis2::Real = 1 end

Listing 8-5: Defining an Ellipse type with @kwdef

This definition shows the second convenient feature of @kwdef: we can supply default values for fields. We also have the option to define a mutable struct with @kwdef mutable struct.

Let’s make an ellipse and assign it to a variable:

julia> oval = Ellipse(axis2=2.6) Ellipse(1, 2.6) julia> oval.axis1, oval.axis2 (1, 2.6)

This example shows how we can supply a subset of the type’s keyword arguments, and the ones we omit will get their default arguments. As with functions, any keyword argument without a default in the type definition must be supplied when using the constructor. Also, similarly to functions, we may not mix positional and keyword forms:

julia> Ellipse(2, 3) Ellipse(2, 3) julia> Ellipse(2, axis2=3) ERROR: MethodError: no method matching Ellipse(::Int64; axis2=3)

As there is no drawback to using @kwdef when defining composite types, it’s convenient to use it routinely.

Because of the way Julia’s JIT compiler works with the type system, computing with user-defined types is as fast as using native types. We can work at a higher level of abstraction, creating a set of types that naturally conform to the objects in our problem, without any compromise in performance.



Download



Copyright Disclaimer:
This site does not store any files on its server. We only index and link to content provided by other sites. Please contact the content providers to delete copyright contents if any and email us, we'll remove relevant links or contents immediately.